package com.xlh.entity;

import cn.hutool.core.util.ObjectUtil;
import com.xlh.constant.UserConstant;
import com.xlh.exception.GlobalException;
import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 图片验证码
 * <p>
 * Created by lx on 2019/1/25.
 */
@Data
public class ImageCode {

    /**
     * 验证码
     */
    private String code;

    /**
     * 过期时间
     */
    private LocalDateTime expireTime;

    public ImageCode(String code, int expireIn) {
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
    }

    public boolean isExpired() {
        return LocalDateTime.now().isAfter(expireTime);
    }


    public static boolean checkCode(String verificationCode, HttpServletRequest request){

        HttpSession session = request.getSession();
        ImageCode imageCode = (ImageCode) session.getAttribute(UserConstant.CODE_SESSION_KEY);
        if(ObjectUtil.isNull(imageCode)){
            throw new GlobalException("验证码已经失效");
        }
        return verificationCode.equals(imageCode.getCode());
    }


}
